/**
 * Created by spatra on 14-11-8.
 */

define(['lessonJS/module'], function(lessonModule){

  lessonModule.controller('LessonShowController', ['$scope', '$stateParams', 'currLesson',
    function($scope, $stateParams, currLesson){

      $scope.currLesson = currLesson;
      $scope.navItems = [
        {label: '课程信息', uiSref: 'lesson.show.info'},
        {label: '学生列表', uiSref: 'lesson.show.student'},
        {label: '课程讨论', uiSref: 'lesson.show.discussion'},
        {label: '课程资源', uiSref: 'lesson.show.resource'}
      ];

      $scope.goBack = function(){
        $scope.$emit('goBackService', 'goBackToModule:lesson.list', 'lesson.list.all');
      };
  }]);

  lessonModule.controller('LessonCreatingController', ['$scope', '$state', '$upload', 'LessonService',
    function($scope, $state, $upload, LessonService){
      $scope.addLesson = {};

      $scope.add = function(){
        LessonService.accessor.store($scope.addLesson)
          .success(function(data){
            $scope.$emit('message:success', {
              title: '操作成功',
              msg: '课程已创建'
            });
            $state.go('lesson.show.info', {
              lessonId: data.id
            });
          })
          .error(function(data){
            $scope.$emit('message:error', {
              title: '操作失败',
              msg: data.error
            });
          });
      };

      $scope.reset = function(){
        $scope.addLesson = {};
      };

      $scope.files = [];
      $scope.allowedUpload = true;
      $scope.$watch('files', function() {
        $scope.files.forEach(function (currentFile) {

          $scope.allowedUpload = false;

          $scope.upload = $upload.upload({
            url: LessonService.getTempCoverUri(),
            method: 'post',
            data: {myObj: $scope.myModelObj},
            file: currentFile
          })
            .success(function(data){
              $scope.allowedUpload = true;
              $scope.addLesson.cover = data['filename'];
              $scope.$emit('message:success', {
                msg: '操作成功'
              });
            })
            .error(function(data){
              $scope.$emit('message:error', {
                title: '上传出错',
                msg: data.error
              })
            });
        });

      });

  }]);

  lessonModule.controller('LessonListController', ['$scope', 'lessonList', 'tabName', 'LessonService', 'LessonStudentService',
    function($scope, lessonList, tabName, LessonService, LessonStudentService){
      $scope.tabName = tabName;
      $scope.lessonList = lessonList;

      function reloadLessonList(condName){
          return LessonService.accessor.get({
            params: {cond: condName}
          }).then(function (resp) {
            $scope.lessonList = resp.data;
          }, function (resp) {
            console.error(resp);
            $scope.$emit('message:error', {
              title: '出错了..',
              msg: resp.data.error
            });
          });
      }

      $scope.join = function(lessonId){
        var accessor = LessonStudentService.init({lessonId: lessonId});
        accessor.store().then(
          function(resp){
            reloadLessonList('other');
            $scope.$emit('message:success', {
              title: '操作成功',
              msg: '课程已申请加入，请等待老师审核'
            });
          },
          function(resp){
            console.error(resp);
            $scope.$emit('message:error', {
              title: '出错了..',
              msg: resp.data.error
            });
          }
        );
      };

      $scope.exit = function(lessonId){
        var accessor = LessonStudentService.init({lessonId: lessonId});
        accessor.destroy().then(
          function(resp){
            reloadLessonList('exit');
            $scope.$emit('message:success', {
              title: '操作成功',
              msg: '课程已申请退出，请等待老师审核'
            });
          },
          function(resp){
            console.error(resp);
            $scope.$emit('message:error', {
              title: '出错了..',
              msg: resp.data.error
            });
          }
        );
      };

  }]);

  lessonModule.controller('LessonInfoController', ['$scope', '$stateParams', 'currLesson', 'LessonResourceService',
    function($scope, $stateParams, currLesson, LessonResourceService) {
      LessonResourceService.accessor['setParentResourceId']($stateParams);

      $scope.lesson = currLesson;

      $scope.download = function(resourceId){
        LessonResourceService.downloadResource(resourceId);
      };

    }]);

  lessonModule.controller('LessonStudentController', ['$scope', '$stateParams', 'studentList', 'LessonStudentService', 'LoginStatusService',
    function($scope, $stateParams, studentList, LessonStudentService, LoginStatusService){

      $scope.students = studentList;

      var userRole = LoginStatusService.get('personalInfo.role.name');

      function reloadStudents()
      {
        var accessor = LessonStudentService.init($stateParams['lessonId']);
        accessor.get().then(
          function(resp){
            $scope.students = resp.data;
          },function(resp){
            console.log('error');
          })
      }

      $scope.applyIn = function(studentId){
        var accessor = LessonStudentService.init($stateParams['lessonId']);
        if ( userRole == 'teacher' ){
          return accessor.update(studentId, { status: 1 })
            .then(function(resp){
              reloadStudents();
            },function(resp){
              console.log(resp.data);
            })
        } else {
          return accessor.update(studentId, { status: 2 })
            .then(function(resp){
              reloadStudents();
            },function(resp){
              console.log(resp.data);
            })
        }
      };

      $scope.applyOut = function(studentId){
        var accessor = LessonStudentService.init($stateParams['lessonId']);
        if ( userRole == 'teacher' ){
          return accessor.destroy(studentId)
            .then(function(resp){
              reloadStudents();
            },function(resp){
              console.log(resp.data);
            })
        } else {
          return accessor.update(studentId, { status: 3 })
            .then(function(resp){
              reloadStudents();
            },function(resp){
              console.log(resp.data);
            })
        }
      }

    }]);


  lessonModule.controller('LessonCallnameController', ['$scope', 'callnameList',
    function($scope, callnameList){
      $scope.callnameList = callnameList;


  }]);

  lessonModule.controller('LessonCallnameShowController', ['$rootScope', '$scope', '$modal', '$state', '$stateParams', 'currentList', 'LessonCallnameStudentsService', 'lessonModuleBaseUrl', 'LessonCallnameDoService',
    function($rootScope, $scope, $modal, $state, $stateParams, currentList, LessonCallnameStudentsService, lessonModuleBaseUrl, LessonCallnameDoService){
      LessonCallnameStudentsService.accessor['setParentResourceId']($stateParams);
      $scope.currentList = currentList;

      function getSelected(){
        var rtn = [];
        $scope.currentList['students'].forEach(function(currStu){
          if( currStu['selected'] ){
            rtn.push(currStu);
          }
        });

        return rtn;
      }

      function reloadStudents(){
        LessonCallnameStudentsService.accessor.get()
          .success(function(data){
            $scope.currentList['students'] = data;
          })
          .error(function(data){
            console.error(data);
            $scope.$emit('message:success', {
              msg: '刷新学生列出错'
            });
          })
      }
      reloadStudents();
      $rootScope.$on('callnameStudents:reload', function(){
        reloadStudents();
      });

      $scope.selected= function(currentStudent){
        currentStudent['selected'] = !currentStudent['selected'];
      };

      $scope.selectedAll = function(){
        $scope.currentList.students.forEach(function(student){
          student['selected'] = true;
        });
      };

      $scope.inverseSelected = function(){
        $scope.currentList.students.forEach(function(student){
          student['selected'] = ! student['selected'];
        });
      };

      $scope.destroy = function(){
        if( ! confirm('确定删除？') ){
          return;
        }

        LessonCallnameStudentsService.destroyMany( getSelected() )
          .success(function(){
            reloadStudents();
            $scope.$emit('message:success', {
              msg: '操作成功'
            });
          })
          .error(function(){
            $scope.$emit('message:error',{
              msg: '操作失败'
            })
          });
      };

      $scope.addStudent = function () {

        $scope.addStudentModule = $modal.open({
          templateUrl: lessonModuleBaseUrl + 'tpls/lesson.callnameStudentModal.html',
          controller: 'AddCallnameStudentController',
          size: 'md'
        });

        $scope.addStudentModule.result
          .then(function(data){
            LessonCallnameStudentsService.addStudent(data)
              .success(function(){
                reloadStudents();
                $scope.$emit('message:success', {
                  title: '操作成功',
                  msg: '已成功添加'
                });
              })
              .error(function(data){
                console.error(data);
                $scope.$emit('message:error', {
                  title: '操作失败',
                  msg: data.error
                });
              })
          });
      };

      $scope.callnameMethods = LessonCallnameDoService.getFilterConditions();console.log($scope.callnameMethods);

      $scope.selectedMethod = 'all';
      $scope.changeMethod = function(methodName){
        $scope.selectedMethod = methodName;
      };
      $scope.startCallname = function(){
        console.log($scope.selectedMethod);
        $state.go('lesson.callname.show.do',{
          'callnameId':$stateParams['callnameId'],
          'callnameMethod': $scope.selectedMethod
        });
      };

  }]);

  lessonModule.controller('AddCallnameStudentController', ['$scope', '$upload', '$modalInstance', 'LessonCallnameService',
    function($scope, $upload, $modalInstance, LessonCallnameService){
      $scope.student = {
        number: '',
        name: ''
      };

      $scope.files = [];
      $scope.uploading = false;
      $scope.$watch('files', function() {

        $scope.files.forEach(function (currentFile) {
          $scope.upload = $upload.upload({
            url: LessonCallnameService.getExcelUploadUri(),
            method: 'post',
            data: {myObj: $scope.myModelObj},
            file: currentFile
          })
            .progress(function (evt) {
              $scope.uploading = true;
            })
            .success(function (data) {
              $scope.uploading = false;
              $scope.students = data;
            })
            .error(function (data) {
              $scope.uploading = false;
              $scope.$emit('message:error', {
                title: '操作失败',
                msg: data.error
              });
            });//End of -> files.forEach
        });//End of --> callback of files $watch
      });

      $scope.cancel = function(){
        $modalInstance.dismiss('cancel');
      };

      $scope.ok = function(){
        var data = null;
        if( $scope.students ){
          data = {
            students: $scope.students
          };
        }
        else{
          data = $scope.student
        }
        $modalInstance.close(data);
      }
  }]);

  lessonModule.controller('LessonCallnameCreatingController', ['$scope', '$upload', '$state', 'LessonCallnameService',
    function($scope, $upload, $state, LessonCallnameService){
      var reset = function(){
        $scope.addList = {
          students: []
        };
      };
      reset();
      $scope.reset = reset;

      $scope.files = [];
      $scope.uploading = false;

      $scope.$watch('files', function(){

        $scope.files.forEach(function(currentFile){
          $scope.upload = $upload.upload({
            url: LessonCallnameService.getExcelUploadUri(),
            method: 'post',
            data: {myObj: $scope.myModelObj},
            file: currentFile
          })
            .progress(function(evt){
              $scope.uploading = true;
            })
            .success(function(data){
              $scope.uploading = false;
              console.log(data);
              $scope.addList['students'] = $scope.addList['students'].concat(data);
            })
            .error(function(data){
              $scope.uploading = false;
              $scope.$emit('message:error', {
                title: '操作失败',
                msg: data.error
              });
            });//End of -> files.forEach
        });//End of --> callback of files $watch

      });//End of --> $watch

      $scope.add = function(){
        LessonCallnameService.accessor.store($scope.addList)
          .success(function(data){
            $state.go('lesson.callname.show', {
              callnameId: data.id
            });
          })
          .error(function(data){
            console.error(data);
            $scope.$emit('message:error', {
              title: '操作失败',
              msg: data.error
            })
          });
      };//End of -> function:add
    }]);


  lessonModule.controller('LessonCallnameDoController', ['$scope', '$stateParams', '$timeout', '$interval', 'currentCallnameId', 'currentList', 'LessonCallnameService', 'LessonCallnameDoService',
    function($scope, $stateParams, $timeout, $interval, currentCallnameId, currentList, LessonCallnameService, LessonCallnameDoService){

      /*
       初始化用到的变量
       */
      $scope.currentCallnameId = currentCallnameId; //当前列表id
      $scope.filterName = LessonCallnameDoService.getFilterMethodLabel($stateParams['callnameMethod']);
      $scope.students = LessonCallnameDoService.filterStudents(
        currentList['students'],
        $stateParams['callnameMethod']
      );//当前列表的学生
      $scope.currentList = currentList;             //当前列表（基本信息）
      //点名模式
      $scope.modes = [
        {label: '自动', value: 'auto'},
        {label: '手动', value: 'manual'}
      ];
      //设置默认的点名模式
      $scope.callnameMode = 'auto';
      //控制点名的操作集合
      $scope.handler = {};
      //检控改变
      $scope.$watch('auto', function(newValue, oldValue){
        if( newValue != oldValue ){
          $scope.handler.reset();
        }
      });
      //当前状态（是否进行中）
      $scope.status = '';
      //被标记的学生列表
      $scope.markedStudents = [];


      $scope.save = function(){
        var result = [];
        $scope.markedStudents.forEach(function(curr){
          if( curr['mark'] == 'absent' ){
            result.push( curr['id'] );
          }
        });

        LessonCallnameService.accessor.update(currentCallnameId, {
          'absent_student': result
        })
          .success(function(){
            $scope.$emit('message:success', {
              title: '操作成功',
              msg: '列表已保存'
            });
            $scope.handler.reset();
            $scope.$emit('callnameStudents:reload');
          })
          .error(function(data){
            $scope.$emit('message:error', {
              title: '操作失败',
              msg: data.error
            });
          });
      };

    }]);


  lessonModule.controller('LessonResourceController', ['$scope', '$stateParams', '$upload', 'LessonResourceService', 'resourceList', 'userPrivilege', 'LoginStatusService',
    function($scope, $stateParams, $upload, LessonResourceService, resourceList, userPrivilege, LoginStatusService){
      LessonResourceService.accessor['setParentResourceId']($stateParams);

      $scope.resourceFilterConditions = LessonResourceService.getFilterConditions();

      $scope.filterCondObj = {};
      $scope.userPrivilege = userPrivilege;
      $scope.resourceList = LessonResourceService.filterOnCondition(resourceList, $scope.filterCondObj);
      $scope.currentUserId = LoginStatusService.get('personalInfo.id');

      $scope.$watch('filterCondObj', function(newValue){
        $scope.resourceList = LessonResourceService.filterOnCondition(resourceList, newValue);
      }, true);

      function reloadResource(){
        return LessonResourceService.accessor.get()
          .then(function(resp){
            console.log(resp);
            $scope.resourceList = LessonResourceService.filterOnCondition(resp.data['resources'], $scope.filterCondObj) },
          function(resp){
            alert('加载资源出错');
            console.error(resp.data);
          });
      }

      $scope.delete = function(resourceId){
        if( ! confirm("您确实要删除吗？") ){
          return;
        }

        LessonResourceService.accessor.destroy(resourceId)
          .then(function(){
            reloadResource();
          },function(resp){
            $scope.$emit('message:error', {
              title: '操作失败',
              msg: resp.data.error
            });
          });
      };

      $scope.download = function(resourceId){
        LessonResourceService.downloadResource(resourceId);
      };

      /*
       实现文件上传
       */
      $scope.files = [];  //用于文件上传
      $scope.uploadings = {};
      $scope.$watch('files', function(){
        $scope.files.forEach(function(currentFile){
          var filename = currentFile.name;

          $scope.uploadings[filename] = {
            filename: filename
          };

          $scope.upload = $upload.upload({
            url: LessonResourceService.getUploadUri(),
            method: 'post',
            data: {myObj: $scope.myModelObj},
            file: currentFile
          })
            .progress(function(evt){
              $scope.uploadings[filename]['value'] = parseInt(100.0 * evt.loaded / evt.total);
            })
            .success(function(){
              reloadResource();
              delete $scope.uploadings[filename];
              $scope.$emit('message:success', {
                title: '操作成功',
                msg: '文件已上传'
              })
            })
            .error(function(data){
              delete $scope.uploadings[filename];
              $scope.$emit('message:error', {
                title: '操作失败',
                msg: data.error
              });
            })
        });
      });

    }]);//End of --> LessonResourceController
});
